import { useRequest } from 'ahooks';
import { Button, Form, Input, Typography } from 'antd';
import { useTranslation } from 'react-i18next';

import { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import csrfCode from '@/pages/vulnerable/code/csrf';
import messageBox from '@/utils/messageBox';

import { changePwdMid, CsrfChangePwd } from '../../service';
const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: csrfCode.mid,
};

const Vulnerable: React.FC = () => {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const { run: changePwd, loading } = useRequest(
    async (params: CsrfChangePwd = form.getFieldsValue()) => {
      await changePwdMid(params).then(res => {
        messageBox.success({ content: res.msg });
      });
    },
    { manual: true },
  );

  return (
    <>
      <Title level={4} italic>
        {t('passwordChange')}
      </Title>
      <Form
        initialValues={{
          csrfToken: 'hahahahaha',
        }}
        onFinish={changePwd}
        form={form}
        layout="vertical"
      >
        <Form.Item required rules={[{ required: true }]} name="username" label={t('username')}>
          <Input placeholder={t('usernamePlaceholder') as string} />
        </Form.Item>
        <Form.Item
          required
          rules={[{ required: true }]}
          name="newPassword"
          label={t('passwordChangeNew')}
        >
          <Input placeholder={t('passwordPlaceholder') as string} />
        </Form.Item>
        <Form.Item hidden noStyle name="csrfToken">
          <Input value="hahahahaha" />
        </Form.Item>
      </Form>
      <Button onClick={() => form.submit()} loading={loading}>
        {t('passwordChange')}
      </Button>
    </>
  );
};

const CsrfMid: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'csrf',
    hasCompare: true,
    solutions: 3,
  },
};

export default CsrfMid;
